package com.sise.netty.server端和client端通信案例;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author idea
 * @data 2019/4/14
 */
@ChannelHandler.Sharable
public class ServerHandle extends SimpleChannelInboundHandler {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接受信息处理器");
        ByteBuf readByteBuf = (ByteBuf) msg;
        byte[] tempDates = new byte[readByteBuf.readableBytes()];
        readByteBuf.readBytes(tempDates);
        String message = new String(tempDates, "UTF-8");
        System.out.println("from client " + message);
        if ("exit".equals(message)) {
            ctx.close();
            return;
        }
        String result = "server message to client";
        //写入缓冲区并行刷新发送
        ctx.writeAndFlush(Unpooled.copiedBuffer(result.getBytes("UTF-8")));
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel=ctx.channel();
        if(channel.isActive()){
            ctx.close();
        }
    }

}
